/**
 * Created by Liran on 2018/12/12.
 */
import Vue from "vue";
import axios from "axios";
import qs from "qs";

// window.root = process.env.API_HOST;
// if (root === undefined) {
//   root = "/core/"
// }

// if (window.root === undefined) {
//   root = "/plugins/"
// }
// root = "http://localhost:9999";
//打包
// root = "http://10.200.62.172:9999";
//开发
root = window.root;

/** **** 创建axios实例 ******/
const service = axios.create({
  baseURL: root, // api的base_url
  // headers: {'X-Requested-With': 'XMLHttpRequest', 'Content-Type': 'application/x-www-form-urlencoded'},
  headers: { "Content-Type": "application/x-www-form-urlencoded" },
  // headers: {'Accept': 'application/vdn.villa.api+json;charset=UTF-8', 'Content-Type': 'application/vdn.villa.api+json;charset=UTF-8'},
  withCredentials: true,
  timeout: 0, // 请求超时时间
});
/** **** 创建axios application/json数据请求实例 ******/
const serviceForJson = axios.create({
  baseURL: root, // api的base_url
  headers: {
    "X-Requested-With": "XMLHttpRequest",
    "Content-Type": "application/json",
  },
  withCredentials: true,
  timeout: 0, // 请求超时时间
});

let loadingState = false;
// 取消请求
let CancelToken = axios.CancelToken;
// 开始设置请求 发起的拦截处理
// config 代表发起请求的参数的实体
service.interceptors.request.use(
  (config) => {
    let requestName;
    console.log(window.sessionStorage.getItem("X-Auth-Token"));
    config.headers["X-Auth-Token"] = JSON.parse(
      window.sessionStorage.getItem("X-Auth-Token")
    );
    if (window.sessionStorage.getItem("X-Auth-Token")) {
      config.headers["Accept"] = "application/vdn.villa.api+json;charset=UTF-8";
    }
    console.log(config);
    if (config.method === "post") {
      console.log(!config.url.includes("api-vss/login"));
      if (!config.url.includes("api-vss/login")) {
        config.headers["Accept"] =
          "application/vdn.villa.api+json;charset=UTF-8";
        config.headers["Content-Type"] = "application/json";
        console.log(config.headers);
      }
      config.data = qs.stringify({
        ...config.data,
      });
      if (config.data && config.data.requestName) {
        requestName = config.data.requestName;
      } else {
        requestName = new Date().getTime();
      }
    } else {
      // config.headers['Accept'] = 'application/vdn.villa.api+json;charset=UTF-8'
      if (config.params && config.params.requestName) {
        requestName = config.params.requestName;
      } else {
        requestName = new Date().getTime();
      }
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 请求到结果的拦截处理
service.interceptors.response.use(
  (response) => {
    // 返回请求正确的结果
    response.headers["Content-Type"] =
      "application/vdn.villa.api+json;charset=UTF-8";
    response.headers["Accept"] = "application/vdn.villa.api+json;charset=UTF-8";
    console.log(response);
    return response;
  },
  (error) => {
    console.log('11111111',error.response);
    // 错误的请求结果处理，这里的代码根据后台的状态码来决定错误的输出信息
    if (error && error.response) {
      switch (error.response.status) {
        case 400:
          error.message = "错误请求";
          break;
        case 401:
          error.message = "未授权，请重新登录";
          break;
        case 403:
          error.message = "拒绝访问";
          break;
        case 404:
          error.message = "请求错误,未找到该资源";
          break;
        case 405:
          error.message = "请求方法未允许";
          break;
        case 408:
          error.message = "请求超时";
          break;
        case 500:
          error.message = "服务器端出错";
          break;
        case 501:
          error.message = "网络未实现";
          break;
        case 502:
          error.message = "网络错误";
          break;
        case 503:
          error.message = "服务不可用";
          break;
        case 504:
          error.message = "网络超时";
          break;
        case 505:
          error.message = "http版本不支持该请求";
          break;
        case 506: //自行扩展的错误码
          error.message = "文件获取失败";
          break;
        default:
          error.message = `连接错误${error.response.status}`;
      }
    } else {
      error.message = "连接到服务器失败";
    }
    // Vue.prototype.publicModal.$emit("loading", false);
    // Vue.prototype.publicModal.$emit("tips", {
    //   show: true,
    //   publicModalMessage: error.message,
    //   fontIcon: "errorWarning",
    // });
    return Promise.reject(error.message);
  }
);
// 将axios 的 post 方法，绑定到 vue 实例上面的 $post
Vue.prototype.$post = function (url, params, headerData) {
  return new Promise((resolve, reject) => {
    service
      .post(url, params, headerData, {
        xhrFields: {
          withCredentials: true,
          useDefaultXhrHeader: true,
        },
      })
      .then((res) => {
        if (res.data === "sessionTimeout") {
          Vue.prototype.publicModal.$emit("loading", false);
          Vue.prototype.publicModal.$emit("sessionTips", {
            show: true,
            publicModalMessage: "会话超时请重新登录！",
            fontIcon: "errorWarning",
            modalType: "session",
          });
          return false;
        }
        resolve(res);
      })
      .catch((err) => {
        // Vue.prototype.publicModal.$emit('loading', false);
        // Vue.prototype.publicModal.$emit('tips', {
        //   show: true,
        //   publicModalMessage: "服务器异常，请稍后重试！",
        //   fontIcon: "errorWarning"
        // });
        // return false;
      });
  }).catch(function (reason) {
    console.log("catch:", reason);
  });
};
// 将axios 的post application/json方式请求，绑定到 vue 实例上面的 $post
Vue.prototype.$postForJson = function (url, params, headerData) {
  return new Promise((resolve, reject) => {
    serviceForJson
      .post(url, params, headerData, {
        xhrFields: {
          withCredentials: true,
          useDefaultXhrHeader: true,
        },
      })
      .then((res) => {
        if (res.data === "sessionTimeout") {
          Vue.prototype.publicModal.$emit("loading", false);
          Vue.prototype.publicModal.$emit("sessionTips", {
            show: true,
            publicModalMessage: "会话超时请重新登录！",
            fontIcon: "errorWarning",
            modalType: "session",
          });
          return false;
        }
        resolve(res);
      })
      .catch((err) => {
        // Vue.prototype.publicModal.$emit('loading', false);
        // Vue.prototype.publicModal.$emit('tips', {
        //   show: true,
        //   publicModalMessage: "服务器异常，请稍后重试！",
        //   fontIcon: "errorWarning"
        // });
        // return false;
      });
  }).catch(function (reason) {
    console.log("catch:", reason);
  });
};

// 将axios 的post application/json方式请求，上传文件
Vue.prototype.$uploadFile = function (url, params, fileHeaderDatas) {
  return new Promise((resolve, reject) => {
    serviceForJson
      .post(url, params, fileHeaderDatas, {
        xhrFields: {
          withCredentials: true,
          useDefaultXhrHeader: true,
        },
        processData: false,
        contentType: false,
      })
      .then((res) => {
        if (res.data === "sessionTimeout") {
          Vue.prototype.publicModal.$emit("loading", false);
          Vue.prototype.publicModal.$emit("sessionTips", {
            show: true,
            publicModalMessage: "会话超时请重新登录！",
            fontIcon: "errorWarning",
            modalType: "session",
          });
          return false;
        }
        resolve(res);
      })
      .catch((err) => {
        // Vue.prototype.publicModal.$emit('loading', false);
        // Vue.prototype.publicModal.$emit('tips', {
        //   show: true,
        //   publicModalMessage: "服务器异常，请稍后重试！",
        //   fontIcon: "errorWarning"
        // });
        // return false;
      });
  }).catch(function (reason) {
    console.log("catch:", reason);
  });
};

// 将axios 的 get 方法，绑定到 vue 实例上面的 $get
Vue.prototype.$get = function (url, params) {
  console.log(url, 689);
  return new Promise((resolve, reject) => {
    service
      .get(url)
      .then((res) => {
        if (res.data === "sessionTimeout") {
          Vue.prototype.publicModal.$emit("loading", false);
          Vue.prototype.publicModal.$emit("sessionTips", {
            show: true,
            publicModalMessage: "会话超时请重新登录！",
            fontIcon: "errorWarning",
            modalType: "session",
          });
          return false;
        }
        resolve(res);
      })
      .catch((err) => {
        // Vue.prototype.publicModal.$emit('loading', false);
        // Vue.prototype.publicModal.$emit('tips', {
        //   show: true,
        //   publicModalMessage: "服务器异常，请稍后重试！",
        //   fontIcon: "errorWarning"
        // });
        // return false;
      });
  }).catch(function (reason) {
    console.log("catch:", reason);
  });
};
Vue.prototype.$getPic = function (url, params) {
  return new Promise((resolve, reject) => {
    service
      .get(url, {
        params: { requestName: "get" },
        responseType: "arraybuffer",
      })
      .then((res) => {
        if (res.data === "sessionTimeout") {
          Vue.prototype.publicModal.$emit("loading", false);
          Vue.prototype.publicModal.$emit("sessionTips", {
            show: true,
            publicModalMessage: "会话超时请重新登录！",
            fontIcon: "errorWarning",
            modalType: "session",
          });
          return false;
        }
        resolve(res);
      })
      .catch((err) => {
        reject(err);
      });
  }).catch(function (reason) {
    console.log("catch:", reason);
  });
};
// 将axios 的 delete 方法，绑定到 vue 实例上面的 $delete
Vue.prototype.$delete = function (url, params) {
  return new Promise((resolve, reject) => {
    service
      .delete(url, {
        params: {},
      })
      .then((res) => {
        if (res.data === "sessionTimeout") {
          Vue.prototype.publicModal.$emit("loading", false);
          Vue.prototype.publicModal.$emit("sessionTips", {
            show: true,
            publicModalMessage: "会话超时请重新登录！",
            fontIcon: "errorWarning",
            modalType: "session",
          });
          return false;
        }
        resolve(res);
      })
      .catch((err) => {
        // Vue.prototype.publicModal.$emit('loading', false);
        // Vue.prototype.publicModal.$emit('tips', {
        //   show: true,
        //   publicModalMessage: "服务器异常，请稍后重试！",
        //   fontIcon: "errorWarning"
        // });
        // return false;
      });
  }).catch(function (reason) {
    console.log("catch:", reason);
  });
};

export default service;
